<template>
    <el-dialog :model-value="dialogVisible" :title="type == 'add' ? '新增' : '编辑'" width="800px"
        :before-close="handleClose" append-to-body>
        <el-form ref="formRef" :model="dataForm" label-width="100px" :rules="rules" :inline="false">
            <el-form-item label="名称" prop="categoryName">
                <el-input v-model="dataForm.categoryName" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
                <el-row style="width:100%;border:1px solid #dcdfe6;border-radius:5px;">
                    <el-col :span="12">
                        <div class="tabs">
                            <p :class="[index == tabNum ? 'active' : '']" v-for="(item, index) in tabsList" :key="index"
                                @click="tabsHandleClick(index)">{{ item }}</p>
                        </div>
                        <div class="city-box">
                            <div class="search-input">
                                <el-input placeholder="输入城市名称搜索" v-model="filterText"></el-input>
                            </div>

                            <el-tree class="filter-tree" :data="dataSource" :props="defaultProps" 
                                :filter-node-method="filterNode" ref="treeRef" node-key="id" show-checkbox
                                @check="currentChange"></el-tree>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="head">
                            <p>已选 : {{ cityList.length }}</p>
                            <p @click="clearCity">清空</p>
                        </div>
                        <div class="selec-city">
                            <p v-for="(item, index) in cityList" :key="index">
                                <span>{{ item.areaName }}</span>
                                <img :src="delIcon" alt @click="deleCity(index)" />
                            </p>
                        </div>
                    </el-col>
                </el-row>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import delIcon from '@/assets/images/del.png'
import { treeData } from '@/util/index'
import { unique } from '@/util/index'
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    type: {
        default: 'add',
        type: String

    },
    dataForm: {
        type: Object,
        default: () => { }
    },

})

const tabsList = ref(['国内', '国外'])


const date = ref([])

const rules = reactive({
    categoryName: [
        { required: true, message: '请输入', trigger: 'blur' },
        { min: 2, max: 18, message: '请输入2-18个字符', required: true, trigger: 'blur' }
    ]
})

const cityList = ref([])
const defaultProps = ref({
    label: 'areaName',
    children: 'children',

})
const dataSource = ref([])

const activeName = ref('false')

const treeRef = ref()

const filterText = ref('')

const formRef = ref(null)

const emit = defineEmits(['on-submit', 'handleClose'])

const tabNum = ref(0)

const cityListOut = ref([]) // 国外选择的城市

const cityListInner = ref([]) // 国内选择的城市

const dataSourceOut = ref([]) // 国外树数据

const dataSourceInner = ref([]) // 国内树数据



onMounted(() => {
    getList(false)
    getList(true)
    if (props.type == 'edit') {
        console.log(props.dataForm.id)
        getDetail(props.dataForm.id)
    }


});

watch(() => (filterText.value), (newVal, oldVal) => {
    treeRef.value.filter(newVal)
})
// 获取列表数据
const getList = (oversea) => {
    api.dataMaintenance.cityMangerList({ oversea }).then(res => {
        let result = treeData(res, 'areaCode', 'parentAreaCode')
        if (activeName.value == 'false' && !oversea) dataSource.value = result
        oversea ? dataSourceOut.value = result : dataSourceInner.value = result
    })

}

const getDetail = (id) => {
    api.feeConfig.cityTypeDetail({ id }).then(res => {
        let outList = [], innerList = [], innerIds = [], outIds = []
        res.addressAreaDTOList.forEach(item => {
            if (item.oversea) {
                outList.push(item)
                outIds.push(item.id)
            } else {
                innerList.push(item)
                innerIds.push(item.id)
            }
        })
        cityListInner.value = innerList
        cityListOut.value = outList
        cityList.value = innerList
        treeRef.value.setCheckedKeys(innerIds)


    })
}


// 关闭
const handleClose = () => {
    formRef.value.resetFields()
    formRef.value.clearValidate()
    emit('handleClose')

}

const tabsHandleClick = (index) => {
    console.log(cityListOut.value)
    let ids = []
    tabNum.value = index
    activeName.value = index == 0 ? 'false' : 'true'
    dataSource.value = index == 0 ? dataSourceInner.value : dataSourceOut.value
    cityList.value = index == 0 ? cityListInner.value : cityListOut.value
    cityList.value.forEach(item => ids.push(item.id))
    treeRef.value.setCheckedKeys(ids)
}

// 城市搜索
const filterNode = (value, data) => {
    if (!value) return true
    return data.areaName.includes(value)
}

// 删除已选的城市
const deleCity = (index) => {
    cityList.value.splice(index, 1)
    let ids = []
    cityList.value.forEach(item => ids.push(item.id))
    treeRef.value.setCheckedKeys(ids)
}

// 清空城市
const clearCity = () => {
    ElMessageBox.confirm(
        '您确定要进行清空操作吗?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            cityList.value = []
            if (activeName.value == 'true') {
                dataSourceOut.value = []
                treeRef.value.setCheckedKeys([])
            } else {
                cityListInner.value = []
                treeRef.value.setCheckedKeys([])
            }
        })
}

// 选中城市
const currentChange = (node, nodeObj, child) => {

    let list = []
    list = treeRef.value.getCheckedNodes().filter((item) => item['areaType'] == 'city')
    console.log(activeName.value)
    if (activeName.value == 'true') {
        // 国外
        cityListOut.value = list
    } else {
        cityListInner.value = list
    }
    cityList.value = list
}

const submit = () => {
    if (!formRef) return
    formRef.value.validate(valid => {
        if (valid) {
            const obj = {
                'add': 'cityTypeAdd',
                'edit': 'cityTypeEdit'
            }
            const { categoryName, id } = props.dataForm
            if (cityList.value.length == 0) return ElMessage.error('请选择城市')
            let addressAreaIds = [], addressAreaNames = []
            let allCityList = [...cityListInner.value, ...cityListOut.value]
            allCityList.forEach(item => {
                addressAreaIds.push(item.id)
                addressAreaNames.push(item.areaName)
            })
            let data = {
                categoryName,
                addressAreaIds,
                addressAreaNames
            }
            if (props.type == 'edit') data['id'] = id

            api.feeConfig[obj[props.type]](data).then(res => {
                emit('on-update')
                handleClose()
                ElMessage.success('操作成功')
            })


        } else {
            console.log('error submit!')
            return false
        }
    })
}


</script>
<style lang="scss" scoped>
.search-input {
    padding: 10px 0;
}

.tabs,
.head {
    display: flex;
    height: 40px;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    width: 100%;
    border-right: 1px solid #dcdfe6;

    p {
        margin: 0;
        font-size: 14px;
        margin: 0 14px;
        cursor: pointer;

        &.active {
            color: #0049ad;
            border-bottom: 1px solid #0049ad;
        }
    }
}

.head {
    border-right: 0;

    p {
        &:nth-child(1) {
            padding-left: 10px;
            flex: 1;
            color: #0049ad;
        }

        &:nth-child(2) {
            text-align: right;
        }
    }
}

.city-box {
    padding-left: 10px;
    border-right: 1px solid #dcdfe6;
    padding-right: 10px;
}

.filter-tree {
    height: 340px;
    overflow-y: auto;
    padding-bottom: 20px;
}

.selec-city {
    padding: 10px 0;
    height: 400px;
    overflow-y: auto;
    padding-bottom: 20px;

    p {
        margin: 0;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5ff;
        padding: 0 10px;

        &:hover {
            background: #dcdfe6;
        }

        span {
            font-size: 14ppx;
            flex: 1;
        }

        img {
            width: 15px;
            height: 15px;
            margin-left: 15px;
            cursor: pointer;
        }
    }
}
</style>
